/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import axios from 'axios';
import qs from 'qs';

// Utils
import { Saiku, Settings } from '../utils';

// Constants
const QUERY_URL = 'api/query';

// Axios Cancellation
const CancelToken = axios.CancelToken;
let axiosCancelRequest;

class MemberService {
  static async getMembers({ uuid, hierarchy, level, result, searchlimit }) {
    const url = `${
      Settings.REST_URL
    }/${QUERY_URL}/${uuid}/result/metadata/hierarchies/${encodeURIComponent(
      hierarchy
    )}/levels/${encodeURIComponent(level)}`;
    const data = {
      result,
      searchlimit
    };
    let response;

    try {
      response = await axios.get(url, {
        params: qs.stringify(data),
        cancelToken: new CancelToken(function executor(c) {
          // An executor function receives a cancel function as a parameter
          axiosCancelRequest = c;
        })
      });
    } catch (error) {
      Saiku.axiosHandleErrors(
        'services → MemberService.js → getMembers()',
        error
      );
    }

    return response;
  }

  static cancelRequest() {
    // Cancel the axios request
    // Reference: https://github.com/axios/axios#cancellation
    axiosCancelRequest();
  }
}

export default MemberService;
